package com.yiren.dbaa.module.help_center.api.impl;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.yiren.dbaa.BuildConfig;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.constant.StringConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.net.oss.IOssFileOperationApi;
import com.yiren.dbaa.net.interf.OssFileCallback;
import com.yiren.dbaa.net.oss.impl.OssFileOperationApiImpl;
import com.yiren.dbaa.module.help_center.api.ISoftUpdate;
import com.yiren.dbaa.module.help_center.bean.DeviceUpdateBean;
import com.yiren.dbaa.module.device.dialog.SoftwareUpdateDialog;
import com.yiren.dbaa.util.DeviceUtil;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.io.File;

/**
 * @author lwb
 * @date : 2022/7/25 17:50
 * @description: 检测升级实现类
 */
public class SoftUpdateImpl implements ISoftUpdate {

    private Activity activity;
    private IOssFileOperationApi iOssFileOperationApi;
    private boolean isUpdateHand;   //是否手动更新
    private SoftwareUpdateDialog softwareUpdateDialog;

    public SoftUpdateImpl(Activity activity) {
        this.activity = activity;
        iOssFileOperationApi = new OssFileOperationApiImpl(activity);
        softwareUpdateDialog = new SoftwareUpdateDialog(activity);
    }

    @Override
    public void checkSoftUpdate(boolean isUpdateHand) {
        this.isUpdateHand = isUpdateHand;
        if (isUpdateHand) {
            LoadDialog.show(activity, "正在检测更新，请稍后...", true);
        }
        iOssFileOperationApi.downLoadTxtFile(StringConstant.DJ_APK, AddressConstant.APK_CONFIG_URL, new OssFileCallback() {
            @Override
            public void success(String result) {
                LoadDialog.dismiss(activity);
                DeviceUpdateBean apkUpdateBean = new Gson().fromJson(result, DeviceUpdateBean.class);
                if (StringUtils.isNotEmpty(apkUpdateBean.getVersioncode())) {
                    int appVersionCode = DeviceUtil.getAppCode(activity);
                    if (appVersionCode < Integer.parseInt(apkUpdateBean.getVersioncode())) {
                        if (apkUpdateBean.isForce()) {  // 强制自动更新
                            downLoadFileProcess(apkUpdateBean);
                        } else if (apkUpdateBean.isUpdate()) {  // APK提示更新
                            activity.runOnUiThread(()->softwareUpdateDialog.show(apkUpdateBean, new CommonCallBack() {
                                @Override
                                public void complete() {
                                    downLoadFileProcess(apkUpdateBean);
                                }
                            }));
                        } else if (isUpdateHand) {
                            activity.runOnUiThread(()->softwareUpdateDialog.show(apkUpdateBean, new CommonCallBack() {
                                @Override
                                public void complete() {
                                    downLoadFileProcess(apkUpdateBean);
                                }
                            }));
                        }
                    } else {
                        if (isUpdateHand) MessageBox.show(activity, "已是最新版本!");
                    }
                } else {
                    if (isUpdateHand) MessageBox.show(activity, "已是最新版本!");
                }
            }
            @Override
            public void fail(String error) {
                LoadDialog.dismiss(activity);
                File file = new File(AddressConstant.App_Main_Directory() + "dbaf.apk");
                if (file.exists()) {
                    file.delete();
                }
            }
        });
    }
    @Override
    public void downLoadFileProcess(DeviceUpdateBean apkUpdateBean) {
        iOssFileOperationApi.downLoadFile(StringConstant.DJ_APK, AddressConstant.APK_PATH + apkUpdateBean.getApkname(), AddressConstant.fetchAvailableSdcardFolder() + "/yiren/dbaf/", StringConstant.APK_NAME, new OssFileCallback() {
            @Override
            public void contentLength(long total) {
                LoadDialog.dismiss(activity);
                activity.runOnUiThread(()->softwareUpdateDialog.showUpdateProgressDialog((int) total));
            }

            @Override
            public void progress(int len) {
                activity.runOnUiThread(()->softwareUpdateDialog.refreshProgress(len));
            }

            @Override
            public void success(String result) {
                activity.runOnUiThread(()->softwareUpdateDialog.close());
                Intent intent;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
                } else {
                    intent = new Intent(Intent.ACTION_VIEW);
                }
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                Uri uri;
                File file = new File(AddressConstant.fetchAvailableSdcardFolder() + "/yiren/dbaf/", StringConstant.APK_NAME);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID.concat(".provider"), file);
                } else {
                    uri = Uri.fromFile(file);
                }
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
                activity.startActivity(intent);
                android.os.Process.killProcess(android.os.Process.myPid());

            }
            @Override
            public void fail(String error) {
                MessageBox.show(activity,error);
            }
        });


    }


}
